# -*-coding:utf-8 -*-
# Author : Mo
# Data : 2022/2/4 20:53
from django.shortcuts import render,redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyModelForm,PrettyEditModelForm


def pretty_list(request):
    """ 靓号列表 """

    # 创建300条数据
    # for i in range(300):
    #     models.PrettyNum.objects.create(mobile="18188888818",price=10,level=1,status=1)

    # models.PrettyNum.objects.filter(id=12) # 等于12
    # models.PrettyNum.objects.filter(id_gt=12) # 大于12
    # models.PrettyNum.objects.filter(id_gte=12) # 大于等于12
    # models.PrettyNum.objects.filter(id_lt=12) # 小于12
    # models.PrettyNum.objects.filter(id_lte=12) # 小于等于12
    # models.PrettyNum.objects.filter(mobile="1999") #等于
    # models.PrettyNum.objects.filter(mobile__startswith="1999") #筛选出以1999开头
    # models.PrettyNum.objects.filter(mobile__endswith="999") #筛选出以999结尾
    # models.PrettyNum.objects.filter(mobile__contains="999") #筛选出包含999
    # <QuerySet [<PrettyNum: PrettyNum object (1)>]>
    # 方式一
    # q1 = models.PrettyNum.objects.filter(mobile="13798470443",id=1)
    # 方式二
    # data_dict = {"mobile":"13798470443", "id":1}
    # q2 = models.PrettyNum.objects.filter(**data_dict)

    data_dict = {}
    search_data = request.GET.get('q',"")
    if search_data:
        data_dict ["mobile__contains"] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request,queryset)
    context = {
        "search_data":search_data,

        "queryset": page_object.page_queryset,# 分完页的数据
        "page_string": page_object.html(),# 页码
    }

    return render(request,"pretty_list.html",context)


def pretty_add(request):
    """ 添加靓号 """

    if request.method == "GET":
        form = PrettyModelForm()
        return render(request,"pretty_add.html",{"form":form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_add.html", {"form": form})


def pretty_edit(request,nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据ID取数据库获取要编辑的哪一行数据(对象)
        form = PrettyEditModelForm(instance=row_object)
        return render(request, "pretty_edit.html", {"form": form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')